package com.dms.service.impl;

import com.dms.mapper.CollegeManageMapper;
import com.dms.pojo.Class;
import com.dms.pojo.*;
import com.dms.service.CollegeManageService;
import com.dms.utils.ConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @className: CollegeManageServiceImpl
 * @package: com.dms.service.impl
 * @description 院部管理模块业务逻辑实现类
 * @author: sk
 */
@Service
public class CollegeManageServiceImpl implements CollegeManageService {

    @Autowired
    CollegeManageMapper collegeManageMapper;

    /**
     *  模糊分页查询 院部列表集合
     * @param query
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<College> getCollegeListLimit(String query, int pageNum, int pageSize) {
        Map<String, Object> map = new HashMap<String, Object>();
        //计算分页大小
        pageNum = (pageNum - 1) * pageSize;
        map.put("query", query);
        map.put("start", pageNum);
        map.put("size", pageSize);

        return collegeManageMapper.getCollegeListLimit(map);
    }

    /**
     * 获取院部total
     * @param query
     * @return
     */
    @Override
    public int getCollegeTotal(String query) {
        return collegeManageMapper.getCollegeTotal(query);
    }

    /**
     * 检查院部名是否已经存在
     * @param collegeName
     * @return
     */
    @Override
    public boolean checkCollegeName(String collegeName) {
        return collegeManageMapper.getCollegeInfo(collegeName) != null ? false : true;
    }

    /**
     *  添加院部
     * @param college
     * @return
     */
    @Override
    public int addCollege(College college) {
        return collegeManageMapper.addCollege(college);
    }

    /**
     * 获取院部信息
     * @param collegeName
     * @return
     */
    @Override
    public College getCollegeInfo(String collegeName) {
        return collegeManageMapper.getCollegeInfo(collegeName);
    }

    /**
     * 修改院部信息
     * @param college
     * @return
     */
    @Override
    public int editCollege(College college){
        return collegeManageMapper.editCollege(college);
    }

    /**
     * 删除院部信息
     * @param collegeName
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public int deleteCollege(String collegeName) {
        //删除院部
        return collegeManageMapper.deleteCollege(collegeName);
    }

    /****************************************************************************************/

    /**
     * 获取所有学院集合
     * @return
     */
    @Override
    public List<College> getCollegeList() {
        return collegeManageMapper.getCollegeList();
    }

    /**
     * 获取专业列表集合
     * @param select
     * @param query
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<Major> getMajorListLimit(String select, String query, int pageNum, int pageSize) {
        Map<String, Object> map = new HashMap<String, Object>();
        pageNum = (pageNum - 1) * pageSize;
        map.put("select", select);
        map.put("query", query);
        map.put("start", pageNum);
        map.put("size", pageSize);

        List<College> collegeList = collegeManageMapper.getMajorListLimit(map);
        //获取所有专业
        List<Major> majorList = new ArrayList<Major>();
        for (College college : collegeList) {
            for (Major major : college.getMajorList()) {
                majorList.add(major);
            }
        }
        return majorList;
    }

    /**
     * 获取专业列表Total
     * @param select
     * @param query
     * @return
     */
    @Override
    public int getMajorTotal(String select, String query) {
        return collegeManageMapper.getMajorTotal(select, query);
    }

    /**
     * 专业名查重
     * @param majorName
     * @return
     */
    @Override
    public boolean checkMajorIsExist(String majorName) {

        return collegeManageMapper.getMajorInfo(majorName) != null ? false : true;
    }

    /**
     * 添加专业信息
     * @param major
     * @return
     */
    @Override
    public int addMajor(Major major) {
        return collegeManageMapper.addMajor(major);
    }

    /**
     * 获取专业信息
     * @param MajorName
     * @return
     */
    public Major getMajorInfo(String MajorName){
        return collegeManageMapper.getMajorInfo(MajorName);
    }

    /**
     * 修改专业信息
     * @param major
     * @return
     */
    @Override
    public int editMajor(Major major) {
        return collegeManageMapper.editMajor(major);
    }

    /**
     * 删除专业信息
     * @param majorName
     * @return
     */
    @Override
    public int deleteMajor(String majorName) {
        return collegeManageMapper.deleteMajor(majorName);
    }

    /*********************************************************************************************************************/
    /**
     * 获取班级列表集合
     * @param select
     * @param query
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<Class> getClassListLimit(Integer select, String query, int pageNum, int pageSize) {
        pageNum = (pageNum - 1) * pageSize;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("select", select);
        map.put("query", query);
        map.put("start", pageNum);
        map.put("size", pageSize);
        List<Class> classList = collegeManageMapper.getClassListLimit(map);
        //对连表所产生的的无效数据进行解决
        for (Class aClass : classList) {
            int majorId = aClass.getMajorId();
            int classId = aClass.getClassId();
            List<Student> studentList = collegeManageMapper.getClassStudentInfo(majorId, classId);
            aClass.setStudentList(studentList);
        }
        return classList;
    }

    /**
     * 获取班级列表total
     * @param select
     * @param query
     * @return
     */
    @Override
    public int getClassTotal(Integer select, String query) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("select", select);
        map.put("query", query);
        return collegeManageMapper.getClassTotal(map);
    }

    /**
     * 班级查重
     * @param majorId
     * @param className
     * @return
     */
    public boolean checkClass(int majorId, String className) {
        return collegeManageMapper.getClassInfo(majorId, className) != null ? false : true;
    }

    /**
     * 添加班级
     * @return
     */
    @Override
    public int addClass(Class aClass) {
        return collegeManageMapper.addClass(aClass);
    }

    /**
     * 获取班级信息
     * @param majorId
     * @param className
     * @return
     */
    @Override
    public Class getClassInfo(int majorId, String className) {
        return collegeManageMapper.getClassInfo(majorId, className);
    }

    /**
     * 编辑班级信息
     * @param aClass
     * @return
     */
    @Override
    public int editClass(Class aClass) {
        /* 1、根据当前编辑框提交的信息，去获取数据是否存在这样一条数据*/
        /* 2、如果不存在，直接提交修改信息；如果存在， 根据原有Id 获取数据库原本的数据 ，再判断数据查出的className和传过来的className是否一致*/
        /* 3、 如果一致，直接提交修改信息；如果不一致，返回-1，提示当前班级已录入*/
        //获取班级信息
        Class aClass1 = collegeManageMapper.getClassByClassName(aClass.getClassName());
        if (aClass1 == null) {
            return collegeManageMapper.editClass(aClass);
        } else {
            //根据classID查找班级信息
            Class aClass2 = collegeManageMapper.getClassByClassId(aClass.getClassId());
            //核对aClass里面的className是否一致
            //一致：当前要修改的是辅导员
            if (aClass2.getClassName().equals(aClass1.getClassName())) {
                return collegeManageMapper.editClass(aClass);
            } else {//不一致：修改了班级名称
                return -1;
            }
        }
    }

    /**
     * 删除班级信息
     * @param className
     * @return
     */
    @Override
    public int deleteClass(String className) {
        return collegeManageMapper.deleteClass(className);
    }

    /*******************************************************************************************/
    /**
     * 模糊查询学生信息
     * @param majorId
     * @param buildingId
     * @param stuNumber
     * @param stuName
     * @param classId
     * @return
     */
    @Override
    public List<Student> getStudentListLimit(Integer majorId, Integer buildingId, String stuNumber, String stuName, Integer classId,
                                             int pageNum, int pageSize) {
        pageNum = (pageNum - 1) * pageSize;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("majorId", majorId);
        map.put("buildingId", buildingId);
        map.put("stuNumber", stuNumber);
        map.put("stuName", stuName);
        map.put("classId", classId);
        map.put("start", pageNum);
        map.put("size", pageSize);
        return collegeManageMapper.getStudentListLimit(map);
    }

    /**
     * 获取total
     * @param majorId
     * @param buildingId
     * @param stuNumber
     * @param stuName
     * @param classId
     * @return
     */
    @Override
    public int getStudentTotal(Integer majorId, Integer buildingId, String stuNumber, String stuName, Integer classId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("majorId", majorId);
        map.put("buildingId", buildingId);
        map.put("stuNumber", stuNumber);
        map.put("stuName", stuName);
        map.put("classId", classId);
        return collegeManageMapper.getStudentTotal(map);
    }


    /**
     * 获取学生信息
     * @param userName
     * @return
     */
    @Override
    public Student getStudentByUserName(String userName) {
        return collegeManageMapper.getStudentByUserName(userName);
    }

    /**
     * 1、添加学生
     * 2、根据学生学号查询id
     * 3、在user表中插入记录
     * 4、获取当前宿舍的信息，用以判断当前宿舍是否满员
     * 5、更新dormitory表中的已住人数
     * @param student
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public int addStudent(Student student) {
        student.setStuGender(Integer.parseInt(student.getStuIdentityCardNumber().substring(16,17)) % 2 == 0 ? 0 : 1);
        String str = student.getStuIdentityCardNumber();
        student.setStuIdentityCardNumber(str.split("&")[0]);
        String userPassword = str.split("&")[1];
        if (student.getStuIndate() == null || student.getStuIndate().equals(""))
            student.setStuIndate(null);
        System.out.println(student);
        //1、添加学生
        int result = collegeManageMapper.addStudent(student);
        if (result > 0) {
            //2、插入记录、封装user表
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("userName", student.getUserName());
            map.put("userPassword", userPassword);
            map.put("userType", ConstantUtil._USERTYPE_STUDENT); // 2
            map.put("stuId", collegeManageMapper.getStudentByUserName(student.getUserName()).getStuId()); //3、获取id

            result += collegeManageMapper.addStudentUser(map);
        }
        //4、判断宿舍是否满员
        if (student.getDormitoryId() != null){
            Dormitory dormitory = collegeManageMapper.getDormitoryInfo(student.getDormitoryId());
            if (dormitory.getDormitoryLiveIn() == dormitory.getDormitorySpendable()){
                try {
                    int i = 1 / 0;
                }catch (Exception e){
                    new Thread("当前寝室已满员");
                }
            }
            else
                // 5、更新dormitory表中的已住人数
                result += collegeManageMapper.updateLiveIn(student.getDormitoryId());
        }

        return result;
    }

    /**
     * 编辑学生
     *
     * 1、判断当前宿舍是否满员---》满员：210
     * 2、修改student表的信息
     * 3、修改dormitory表，如果是换寝室，则原寝室已住人数减1，当前寝室已住人数加1
     * @param student
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public int editStudent(Student student){
        if (student.getStuIdentityCardNumber() == null ||student.getStuIdentityCardNumber().equals(""))
            student.setStuIdentityCardNumber(null);
        else
            student.setStuGender(Integer.parseInt(student.getStuIdentityCardNumber().substring(16,17)) % 2 == 0 ? 0 : 1);
        //获取学生信息
        Student studentInfo = collegeManageMapper.getStudentByUserName(student.getUserName());
        //根据前端传过来的寝室id获取寝室信息
        Dormitory dormitory = collegeManageMapper.getDormitoryInfo(student.getDormitoryId());
        //如果已住人数等于可住人数，则return
        if (dormitory.getDormitoryLiveIn() == dormitory.getDormitorySpendable())
            return 210;
        int num = 0;
        //只修改床号，则人数不动 ,如果寝室号不同，则进行人数变动
        if (studentInfo.getDormitoryId() != dormitory.getDormitoryId()){
            //之前的寝室
            Map<String, Object> map1 = new HashMap<String, Object>();
            map1.put("operator", "-");
            map1.put("dormitoryId", studentInfo.getDormitoryId());
            num += collegeManageMapper.updateDormitoryLiveIn(map1);
            //修改的
            Map<String, Object> map2 = new HashMap<String, Object>();
            map2.put("operator", "+");
            map2.put("dormitoryId", dormitory.getDormitoryId());
            num += collegeManageMapper.updateDormitoryLiveIn(map2);
        }

        //修改学生信息
        num = collegeManageMapper.editStudent(student);

        return num;
    }

    /**
     * 删除学生
     * @param userName
     * @param dormitoryId
     * @param stuName
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public int deleteStudent(String userName, Integer dormitoryId, String stuName) {
        int num = 0;
        if (dormitoryId != null){
            //获取寝室信息
            Dormitory dormitory = collegeManageMapper.getDormitoryInfo(dormitoryId);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("dormitoryId", dormitoryId);
            map.put("operator", "-");
            //如果当前删除的学生是宿舍长，则设为空
            if (stuName.equals(dormitory.getDormitoryHeadOfTheDormitory())){
                map.put("headOfTheDormitory", null);
            }
            //更新宿舍信息
            num = collegeManageMapper.updateDormitoryLiveIn(map);
        }
        num += collegeManageMapper.deleteStudent(userName);
        return num;
    }
}
